import { renderToString } from "vue/server-renderer";
import { createMainApp } from "./main.js";
import fs from "node:fs";
import { useSSRContext } from "vue";

// get BUILD_CONFIG
let profileCode = fs.readFileSync(
	import.meta.env.DEV //
		? new URL("../public/profile.js", import.meta.url).href.replace("file:///", "")
		: "profile.js",
	"utf-8"
);

const BUILD_CONFIG = eval(profileCode + ";BUILD_CONFIG");

export async function render(url: string, manifest: Record<string, any>) {
	console.log("#url: " + url);

	const { app, router } = await createMainApp(BUILD_CONFIG, url);

	// let push = router.replace;
	// if (!push.replace) {
	// 	router.replace = (...args) => {
	// 		console.log("push to: ", url, args);
	// 		push.call(router, ...args);
	// 	};
	// 	router.push.replace = true;
	// }
	router.beforeEach((to, from, next) => {
		console.log("router to: " + url + " => " + to.fullPath);
		next();
	});

	// passing SSR context object which will be available via useSSRContext()
	// @vitejs/plugin-vue injects code into a component's setup() that registers
	// itself on ctx.modules. After the render, ctx.modules would contain all the
	// components that have been instantiated during this render call.
	const context = { ssr_state: { state: {} } };
	const html = await renderToString(app, context);

	return { html, context };
}
